<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    <input type="button" value="初始化购物车" id="reset">
    <table border="1" width="500">
        <thead>
            <tr>
                <th>选中</th>
                <th>名称</th>
                <th>价格</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2"><input type="checkbox" id="allCheck"><label for="allCheck">全选</label></td>
                <td colspan="2">总数量：<span id="allNum">0</span></td>
                <td>总价：<span id="allPrice">0</span></td>
                <td id="allDel">批量删除</td>
            </tr>
        </tfoot>
    </table>
</body>
<script src="./cookie.js"></script>
<script>
    // 初始化购物车（测试用）
    $("#reset").onclick = function(){
        const data = [{
            proName:"手机",
            price:2999,
            num:3,
            proId:"235235",
            flag:true
        },{
            proName:"电脑",
            price:3999,
            num:2,
            proId:"asgdfg",
            flag:true
        },{
            proName:"冰箱",
            price:1999,
            num:5,
            proId:"765q7w864e",
            flag:false
        },{
            proName:"洗衣机",
            price:999,
            num:1,
            proId:"65aesgrjh",
            flag:true
        }];
        // 准备数据，将数据存储在本地存储中
        cookie.setItem("goodsMsg", JSON.stringify(data));
        // 刷新页面
        location.reload();
    }


    

    // 购物车功能

    class Cart{
        constructor(){
            // 1. 获取数据（读取本地存储中的数据）
            this.data = cookie.getItem("goodsMsg") ? JSON.parse(cookie.getItem("goodsMsg")) : [];
            this.tbody = $("tbody");
            this.allCheck = $("#allCheck");
            this.allNum = $("#allNum");
            this.allPrice = $("#allPrice");
            this.allDel = $("#allDel");
            this.render();
            this.addEvent();
            this.init();
        }
        computedCount(){
            this.allNum.innerHTML = this.data.reduce((prev,val)=>prev + val.num, 0);
            this.allPrice.innerHTML = this.data.reduce((prev,val)=>prev + (val.num * val.price), 0);
        }
        init(){
            this.allCheck.checked = this.data.every(val=>val.flag)
            // 封装计算总数，总价格
            this.computedCount();
        }
        render(){
            let str = "";
            this.data.forEach(val=>{
                str += `<tr myid="${val.proId}">
                    <td><input type="checkbox" ${val.flag ? 'checked' : ''} class="check"></td>
                    <td>${val.proName}</td>
                    <td class="price">${val.price}</td>
                    <td><input type="number" value="${val.num}" class="num"></td>
                    <td class="subTotal">${ val.num * val.price }</td>
                    <td class="del">删除</td>
                </tr>`
            })
            this.tbody.innerHTML = str;
        }
        addEvent(){
            const that = this;
            this.tbody.addEventListener("change", proxy("check", function(){
                that.id = this.parentNode.parentNode.getAttribute("myid");
                that.setData(i=>{
                    that.data[i].flag = this.checked;
                    that.allCheck.checked = that.data.every(val=>val.flag)
                });
            }));
            this.tbody.addEventListener("input", proxy("num", function(){
                const tr = this.parentNode.parentNode;
                const price = tr.querySelector(".price").innerHTML;
                that.id = tr.getAttribute("myid");

                tr.querySelector(".subTotal").innerHTML = this.value * price;
                
                that.setData(i=>{
                    that.data[i].num = this.value-0;

                    that.computedCount();
                });
            }));
            this.tbody.addEventListener("click", proxy("del", function(){
                that.id = this.parentNode.getAttribute("myid");
                this.parentNode.remove();
                that.setData(i=>{
                    that.data.splice(i, 1);

                    that.computedCount();
                })
            }))
            this.allCheck.onchange = function(){
                const checks = document.querySelectorAll(".check");
                [...checks].forEach(val=>{
                    val.checked = this.checked;
                });
                that.data.forEach(val=>{
                    val.flag = this.checked;
                })

                // 3. 全选时，数据发生修改，同步到本地存储
                cookie.setItem("goodsMsg", JSON.stringify(that.data));
            }
            this.allDel.onclick = function(){
                that.data = that.data.filter(val=>!val.flag)
                
                // 4. 批量删除时，数据发生修改，同步到本地存储
                cookie.setItem("goodsMsg", JSON.stringify(that.data));

                const trs = that.tbody.children;
                [...trs].forEach(val=>{
                    if(val.querySelector(".check").checked){
                        val.remove();
                    }
                })

                that.allCheck.checked = false;
                that.computedCount();
            }
        }
        setData(cb){
            let i = 0;
            this.data.some((val,idx)=>{
                i = idx;
                return val.proId === this.id
            })
            cb(i);
            // 2. 当数据发生修改时，将数据，同步到本地存储中
            cookie.setItem("goodsMsg", JSON.stringify(this.data))
        }
    }
    new Cart;


    function proxy(select, cb){
        return function(eve){
            const e = eve || window.event;
            const target = e.srcElement || e.target;
            if(target.className === select){
                cb.call(target);
            }
        }
    }

    function $(select){
        return document.querySelector(select)
    }
</script>
</html>